package com.regvision.contacts.demo;

import java.util.ArrayList;
import java.util.List;
import com.regvision.contacts.R;
import com.regvision.contacts.main.ContactsApplication;
import com.regvision.contacts.mode.Observable;
import com.regvision.contacts.mode.Observer;
import com.regvision.contacts.service.AllJoynService;
import com.regvision.contacts.utils.Util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("ValidFragment")
public class DemoFragment extends Fragment implements Observer, OnClickListener, OnItemClickListener {

	private Context context;
	private ContactsApplication mContactApplication = null;
	
	private static final int HANDLE_APPLICATION_QUIT_EVENT = 0;
    private static final int HANDLE_CHANNEL_STATE_CHANGED_EVENT = 1;
    private static final int HANDLE_ALLJOYN_ERROR_EVENT = 2;
    
    private TextView tvName;
    private TextView tvHostStatus;
    private TextView tvUserStatus;
    
    private TextView tvToJoin;
    
    private Button btnJoinSession;
    private Button btnLeaveSession;
    
    private List<String> channelList;
    private ChannelAdapter adapter;
    		
	public static DemoFragment newInstance(Context context, 
										ContactsApplication application) {
		return new DemoFragment(context, application);
	}
	
	public DemoFragment(Context context, ContactsApplication application) {
		this.context = context;
		this.mContactApplication = application;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_demo, null);

		initData();

		initView(view);

		return view;
	}

	private void initData() {
//		mContactApplication.addObserver(this);
//		mContactApplication.channel = Util.getDeviceUUID(context);
//		mContactApplication.hostSetChannelName(mContactApplication.channel);
//        mContactApplication.hostInitChannel();
//        
//        channelList = new ArrayList<String>();
//        adapter = new ChannelAdapter(context, R.layout.channel_list_item, channelList);
	}

	private void initView(View view) {
		
	    Button btnStartChannel = (Button) view.findViewById(R.id.btnStartChannel);
	    btnStartChannel.setOnClickListener(this);
	    
	    Button btnStopChannel = (Button) view.findViewById(R.id.btnStopChannel);
	    btnStopChannel.setOnClickListener(this);
	    
	    
		tvName = (TextView) view.findViewById(R.id.tvName);
		tvHostStatus = (TextView) view.findViewById(R.id.tvHostStatus);
		tvUserStatus = (TextView) view.findViewById(R.id.tvUserStatus);
		
		Button btnGetList = (Button) view.findViewById(R.id.btnChannelList);
		btnGetList.setOnClickListener(this);
		
		ListView list = (ListView) view.findViewById(R.id.lvChannelList);
		list.setAdapter(adapter);
		list.setOnItemClickListener(this);
		
		tvToJoin = (TextView) view.findViewById(R.id.tvToJoin);
		
		btnJoinSession = (Button) view.findViewById(R.id.btnJoinSession);
		btnJoinSession.setOnClickListener(this);
		
		btnLeaveSession = (Button) view.findViewById(R.id.btnLeaveSession);
		btnLeaveSession.setOnClickListener(this);
		
	}
	
	private void doStartChannel() {
		mContactApplication.hostStartChannel();
	}
	
	private void doStopChannel() {
		mContactApplication.hostStopChannel();
	}
	
	private void refreshChannelList(List<String> newChannelList) {
		channelList.clear();
		for (String channel : newChannelList) {
			channelList.add(channel);
		}
	}
	
	private void doJoinSession() {
//		mContactApplication.useSetChannelName(mContactApplication.channel);
//		mContactApplication.useJoinChannel();
	}
	
	private void doLeaveSession() {
		mContactApplication.useLeaveChannel();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
			case R.id.btnStartChannel:
				doStartChannel();
				break;
			case R.id.btnStopChannel:
				doStopChannel();
				break;
			case R.id.btnChannelList:
				refreshChannelList(mContactApplication.getFoundChannels());
				adapter.notifyDataSetChanged();
				break;
			case R.id.btnJoinSession:
				doJoinSession();
				break;
			case R.id.btnLeaveSession:
				doLeaveSession();
			default:
				break;
		}
	}
	
	private void updateUserChannelState() {
        AllJoynService.UseChannelState channelState = mContactApplication.useGetChannelState();
        String name = mContactApplication.useGetChannelName();
        if (name == null) {
            name = "Not set";
        }

        switch (channelState) {
        case IDLE:
            tvUserStatus.setText("Idle");
            btnJoinSession.setEnabled(true);
            btnLeaveSession.setEnabled(false);
            break;
        case JOINED:
            tvUserStatus.setText("Joined");
            btnJoinSession.setEnabled(false);
            btnLeaveSession.setEnabled(true);
            break;
        }
    }

	@Override
	public void update(Observable o, Object arg) {
		// TODO Auto-generated method stub
		String qualifier = (String)arg;
		if (qualifier.equals(mContactApplication.HOST_CHANNEL_STATE_CHANGED_EVENT)) {
            Message message = mHandler.obtainMessage(HANDLE_CHANNEL_STATE_CHANGED_EVENT);
            mHandler.sendMessage(message);
        } else if (qualifier.equals(mContactApplication.USE_CHANNEL_STATE_CHANGED_EVENT)) {
            Message message = mHandler.obtainMessage(HANDLE_CHANNEL_STATE_CHANGED_EVENT);
            mHandler.sendMessage(message);
	    }
	}
	
	private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case HANDLE_APPLICATION_QUIT_EVENT:
                {
                	
                }
                break;
            case HANDLE_CHANNEL_STATE_CHANGED_EVENT:
                {
                    updateHostChannelState();
                    
                    updateUserChannelState();
                }
                break;
            case HANDLE_ALLJOYN_ERROR_EVENT:
                {
                	
                }
                break;
            default:
                break;
            }
        }
    };
    
    private void updateHostChannelState() {
        AllJoynService.HostChannelState channelState = mContactApplication.hostGetChannelState();
        String name = mContactApplication.hostGetChannelName();
        tvName.setText(name);
        switch (channelState) {
	        case IDLE:
	            tvHostStatus.setText("Idle");
	            break;
	        case NAMED:
	        	tvHostStatus.setText("Named");
	            break;
	        case BOUND:
	        	tvHostStatus.setText("Bound");
	            break;
	        case ADVERTISED:
	        	tvHostStatus.setText("Advertised");
	            break;
	        case CONNECTED:
	        	tvHostStatus.setText("Connected");
	            break;
	        default:
	        	tvHostStatus.setText("Unknown");
	            break;
        }

    }

	/* (non-Javadoc)
	 * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		String toJoin = adapter.getItem(position);
		tvToJoin.setText(toJoin);
	}
    
}
